﻿using HtmlAgilityPack;
using System.Data;
using System.Drawing.Imaging;
using System.Net;
using System.Text;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Tools
{
    public partial class ZCool : Form
    {
        private ZCoolWebUtils webUtils;
        // 创建ListBox显示图片
        private List<string> _urls;
        private string _title;

        public ZCool()
        {
            InitializeComponent();
            webUtils = new ZCoolWebUtils();
            _urls = new List<string>();

        }


        private void button1_Click(object sender, EventArgs e)
        {
            this.listBox2.Items.Clear();

            var _url = this.textBox1.Text.Trim();
            HtmlWeb web = new HtmlWeb();
            web.OverrideEncoding = Encoding.UTF8; // 设置为UTF-8编码
            HtmlAgilityPack.HtmlDocument doc = web.Load(_url);

            _title = doc.DocumentNode.SelectSingleNode("//title").InnerText;

            var _list = webUtils.ExtractWebpUrlsFromWebPage(doc);

            //var abc=webUtils.ImageList.Images;






            foreach (var _list2 in _list)
            {
                _urls.Add(_list2);
                this.listBox2.Items.Add(_list2);

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var _path = Path.GetDirectoryName(Application.ExecutablePath) + "\\ZCool\\" + _title;
            if (!Directory.Exists(_path))
            {
                Directory.CreateDirectory(_path);
            }


            foreach (var item in _urls)
            {
                WebClient webClient = new WebClient();
                Byte[] imgData = webClient.DownloadData(item);
                Stream ms = new MemoryStream(imgData);
                ms.Position = 0;
                Image img = Image.FromStream(ms);
                img.Save($"{_path}\\{DateTime.Now.ToString("yyyyMMddhhmmss")}.jpg", ImageFormat.Jpeg);
            }
            this.listBox2.Items.Clear();
            MessageBox.Show("下载完成");
        }
    }
}
